package cn.yeziji.forum.utils;

import cn.yeziji.forum.utils.entity.AliOssConfig;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * 阿里云工具类
 *
 * @author gzkemays
 * @since 2022/3/17
 */
@Slf4j
public class AliUtils {
  /**
   * 上传图片中至 oss
   *
   * @param config 阿里云 oss 配置
   * @return 图片请求的地址
   */
  public static String uploadToOss(AliOssConfig config) {
    OSS ossClient = getOssClient(config);
    String savePath =
        config.getSavePath().endsWith("/") ? config.getSavePath() : config.getSavePath() + "/";
    String bucketName = config.getBucketName();
    String ext = Objects.isNull(config.getExt()) ? "" : config.getExt();
    String fileName;
    if (Objects.isNull(config.getFileName())) {
      fileName = savePath + System.currentTimeMillis() + ext;
    } else {
      fileName = savePath + config.getFileName() + ext;
    }
    ossClient.putObject(bucketName, fileName, config.getStream());
    ossClient.shutdown();
    return config.getReturnUrl() + "/" + fileName;
  }

  /**
   * 下载阿里云并保存文件
   *
   * @param config 配置
   * @return {@link String} 返回文件名
   */
  public static String saveFile(AliOssConfig config) {
    OSS ossClient = getOssClient(config);
    try {
      // 目录不存在就创建目录
      File folder = new File(config.getLocalPath());
      if (!folder.exists()) {
        folder.mkdirs();
      }
      // 文件不存在就创建文件
      File file = new File(config.getLocalFilePath());
      if (!file.exists()) {
        file.createNewFile();
      }
      ossClient.getObject(new GetObjectRequest(config.getBucketName(), config.getOssFilePath()), file);
    } catch (OSSException e) {
      log.error("下载 {} 异常 -> {} - {}: {} - {}", config.getOssFilePath(), e.getRequestId(), e.getHostId(), e.getErrorCode(), e.getErrorMessage());
    } catch (ClientException ex) {
      log.error("client ex -> {}", ex.getMessage());
    } catch (IOException fe) {
      log.error("创建 IO 异常 ex -> {}", fe.getMessage(), fe);
    } finally {
      ossClient.shutdown();
    }
    return config.getFileName();
  }

  private static OSS getOssClient(AliOssConfig config) {
    String endPoint = config.getEndPoint();
    String accessKey = config.getAccessKey();
    String security = config.getSecretKey();
    return new OSSClient(endPoint, accessKey, security);
  }
}
